package user_utils

import (
	"context"
	"encoding/json"
	"fmt"
	"hft/Database/admin/user_db"
	"hft/Http/Services/user/user_model"
	"hft/e"
	"hft/global"
	"reflect"
	"strings"
	"time"

	"github.com/bytedance/sonic/encoder"
	"go.mongodb.org/mongo-driver/bson"
)

func GetOriginName(port int, activity string) string {
	var name string = ""
	if activity != "" {
		name = "-" + activity
	}
	switch port {
	case e.PC.Port:
		name = e.PC.Name + name
	case e.H5.Port:
		name = e.H5.Name + name
	case e.WE_APP.Port:
		name = e.WE_APP.Name + name
	case e.BAIDU_APP.Port:
		name = e.BAIDU_APP.Name + name
	case e.PHONE_400.Port:
		name = e.PHONE_400.Name
	case e.TITOK_APP.Port:
		name = e.TITOK_APP.Name + name
	case e.AUTO_RECORD.Port:
		name = e.AUTO_RECORD.Name
	}
	return name
}

// 获取时间差
func GetTimesDistance(a time.Time, b time.Time) int {
	fmt.Println(a.Format("20060102150405"), b.Format("20060102150405"), a.Unix(), b.Unix(), (a.Unix()-b.Unix())/3600)
	var timeSpan = (a.Unix() - b.Unix())
	return int(timeSpan)
}

// 判断
func IsValid(valid bool) int {
	if valid {
		return 1
	} else {
		return 0
	}
}

// 获取时间
func GetTime(data interface{}, Name string) (string, error) {
	valueType := reflect.TypeOf(data) // 使用反射获取结构体类型
	value := reflect.ValueOf(data)    // 使用反射获取结构体值
	for i := 0; i < valueType.NumField(); i++ {
		field := valueType.Field(i)
		fieldValue := value.Field(i)
		if field.Name == Name && field.Type == reflect.TypeOf(time.Time{}) {
			createTimeString := fieldValue.Interface().(time.Time).Format("2006-01-02 15:04:05")
			return createTimeString, nil
		}
	}
	return "", fmt.Errorf("No '%v' field of type 'time.Time' found in the struct", Name)
}

// 获取所属位置
func GetBelongName(belongName string) string {
	var bArr = strings.Split(belongName, "-")
	if len(bArr) == 3 {
		return bArr[len(bArr)-1]
	} else if len(bArr) == 4 {
		return bArr[len(bArr)-2]
	} else {
		return ""
	}
}

// 查询跟进
func FindFollowUp(detail *user_db.User) (list []user_model.FollowUpItem) {
	// 找出跟进列表
	var filter = bson.M{"user_uuid": detail.UUID}
	var followItem user_model.FollowUpItem
	var followList = make([]user_model.FollowUpItem, 0)
	var database = fmt.Sprintf("follow_up_%v", detail.City)
	var collection = fmt.Sprintf("user_uuid_first_%c", detail.UUID[0])
	cursor, err := global.OC_MON1.Database(database).Collection(collection).Find(context.TODO(), filter)
	if err != nil {
		fmt.Println(err)
	}
	var results []bson.M
	if err = cursor.All(context.TODO(), &results); err != nil {
		panic(err)
	}
	for _, result := range results {
		v, err := encoder.Encode(result, encoder.SortMapKeys)
		if err != nil {
			fmt.Printf("%v\n", err)
		}
		json.Unmarshal(v, &followItem)
		followList = append(followList, followItem)
	}
	return followList
}
